package proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description
 * 动态代理
 * 原理：
 * 1.利用的是jdk反射机制
 * 2.动态生成class文件字节流，然后通过loader加载此字节流创建代理类class
 *
 * @Date 2020/7/8 16:28
 * @Author taojiangbing
 */
public class DynamicProxy implements InvocationHandler {

    //代理的对象，即真实的对象
    private Object mObj;

    public DynamicProxy(Object pObj){
        mObj = pObj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        System.out.println("this is Dynamic proxy invode");
        if(mObj != null){
            result = method.invoke(mObj, args);
        }
        return result;
    }

    public static void main(String[] args){
        RealSubject realSubject = new RealSubject();
        DynamicProxy proxy = new DynamicProxy(realSubject);
        Subject subject = (Subject) Proxy.newProxyInstance(
                realSubject.getClass().getClassLoader(),
                realSubject.getClass().getInterfaces(),
                proxy
        );
        subject.test();
    }
}
